package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3ICBomSynService;
import com.ev.k3cloudBusiness.vo.BomDetailVo;
import com.ev.k3cloudBusiness.vo.BomVo;
import com.ev.mes.domain.BomDO;
import com.ev.mes.domain.BomDetailDO;
import com.ev.mes.domain.ProductionFeedingDO;
import com.ev.mes.service.BomDetailService;
import com.ev.mes.service.BomService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 姚家乐
 * @since 2021/6/1 16:57
 */
@Slf4j
@Service
public class K3ICBomSynServiceImpl implements K3ICBomSynService {

    @Autowired
    private BomService               bomService;

    @Autowired
    private BomDetailService         bomDetailService;

    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R bomSyn() {
        String bomResult = kingdeeMiddlewareService.BomAll();

        List<BomDO> bomDOList = bomService.listAll();
        JSONObject resultObj = JSON.parseObject(bomResult);
        if (!resultObj.getString("code").equals("0")) {
            log.info(resultObj.getString("msg"));
            return R.error(resultObj.getString("msg"));
        }
        List<BomVo> bomVOs = JSON.parseArray(resultObj.get("data").toString(), BomVo.class);
        if (bomVOs.size() > 0) {
            Long userId = ShiroUtils.getUserId();

            // 本地生产计划内码
            List<Long> localIdList = bomDOList.stream().map(BomDO::getId).collect(Collectors.toList());
            // K3Cloud生产计划内码
            List<Long> remoteIdList = bomVOs.stream().map(BomVo::getFInterID)
                    .collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
                    .collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains)
                    .collect(Collectors.toList());
            //        // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if (deleteIdList.size() > 0) {
                //批量删除
                List<BomDO> bomDOs=bomDOList.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (BomDO bomDO:bomDOs
                ) {
                    bomDO.setDelFlag(1);
                }
                List<Long> bomIds = bomDOs.stream().map(BomDO::getId).collect(Collectors.toList());
                bomService.batchUpdate(bomDOs);
                bomDetailService.batchUpdateToDelFlagByBomId(bomIds);
                log.info("批量删除");
            }
            Date date = new Date();
            if(updateIdList.size() > 0){
                List<BomVo> bomVoList = bomVOs.stream().filter(e->updateIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<BomDO> bomDOS = bomDOList.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                BomVo bomVo ;
                for (BomDO bomDO : bomDOS) {
                    bomVo = bomVoList.stream().filter(e->bomDO.getId().equals(e.getFInterID())).collect(Collectors.toList()).get(0);
                    bomDO.setSerialno(bomVo.getFBOMNumber());
                    bomDO.setAuditor(bomVo.getFCheckerID());
                    bomDO.setType(bomVo.getFBomType());
                    bomDO.setVersion(bomVo.getFVersion());
                    bomDO.setCount(bomVo.getFQty());
                    bomDO.setMaterielId(bomVo.getFItemID());
                    bomDO.setUpdateBy(userId);
                    bomDO.setUpdateTime(date);
                }
                bomService.batchUpdate(bomDOS);
                bomDetailService.batchRemoveBomId(updateIdList.toArray(new Long[0]));
                List<BomDetailDO> detailDOList = Lists.newArrayList();
                for (BomVo vo : bomVoList) {
                    List<BomDetailVo> icBomChildDOS = vo.getIcBomChildDOS();
                    for (BomDetailVo detailVo : icBomChildDOS) {
                        BomDetailDO detailDO = new BomDetailDO();
                        detailDO.setBomId(detailVo.getFInterID());
                        detailDO.setMaterielId(detailVo.getFItemID());
                        detailDO.setStandardCount(new BigDecimal(detailVo.getFQty()));
                        detailDO.setProcessId(detailVo.getFOperID());
                        detailDO.setMaterielType(detailVo.getFMaterielType());

                        detailDO.setCreateBy(userId);
                        detailDO.setCreateTime(date);
                        detailDO.setUpdateBy(userId);
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }
                bomDetailService.batchSave(detailDOList);
            }
            if (remoteIdList.size() > 0) {
                List<BomVo> bomVos = bomVOs.stream()
                        .filter(e -> remoteIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<BomDO> list = Lists.newArrayList();
                List<BomDetailDO> detailDOList = Lists.newArrayList();
                for (BomVo bomVo : bomVos) {
                    BomDO bomDO = new BomDO();
                    bomDO.setId(bomVo.getFInterID());
                    bomDO.setCreateBy(userId);
                    bomDO.setSerialno(bomVo.getFBOMNumber());
                    bomDO.setAuditor(bomVo.getFCheckerID());
                    bomDO.setType(bomVo.getFBomType());
                    bomDO.setVersion(bomVo.getFVersion());
                    bomDO.setCount(bomVo.getFQty());
                    bomDO.setMaterielId(bomVo.getFItemID());
                    bomDO.setCreateTime(date);
                    bomDO.setUseStatus(1);
                    bomDO.setAuditSign(178L);
                    bomDO.setUpdateBy(userId);
                    bomDO.setUpdateTime(date);
                    bomDO.setDelFlag(0);

                    list.add(bomDO);
                    List<BomDetailVo> detailVos = bomVo.getIcBomChildDOS();
                    for (BomDetailVo detailVo : detailVos) {
                        BomDetailDO detailDO = new BomDetailDO();
                        detailDO.setBomId(detailVo.getFInterID());
                        detailDO.setMaterielId(detailVo.getFItemID());
                        detailDO.setStandardCount(new BigDecimal(detailVo.getFQty()));
                        detailDO.setProcessId(detailVo.getFOperID());
                        detailDO.setMaterielType(detailVo.getFMaterielType());

                        detailDO.setCreateBy(userId);
                        detailDO.setCreateTime(date);
                        detailDO.setUpdateBy(userId);
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }

                if (!CollectionUtils.isEmpty(list)){
                    bomService.batchSave(list);
                    bomDetailService.batchSave(detailDOList);
                }
            }
            log.info("批量新增");
        }
        return R.ok();
    }
}
